<script setup lang="ts">
import {ref} from "vue";
import {getCode, login} from "@/api/login";
import type {AccessToken, Code, LoginParam} from "@/api/login/types";
import type {FormRules} from "element-plus";
import {useRouter, useRoute} from "vue-router";
import {useTokenStore} from "@/stores/tokenStore";

const tokenStore = useTokenStore()

const route = useRoute()
const router = useRouter()


const codeUrl = ref('')

const loginFormRef = ref()
const loginForm = ref<LoginParam>({
  username: '',
  password: '',
  uuid: '',
  code: '',
})

const loginFormRules = ref<FormRules>({
  username: [{required: true, message: '请输入用户名'}],
  password: [{required: true, message: '请输入密码'}],
  code: [{required: true, message: '请输入验证码'}]
})

const getVerifyCode = () => {
  getCode().then((resp: Code) => {
    codeUrl.value = resp.codeUrl
    loginForm.value.uuid = resp.uuid
  }).catch(e => {
    console.log(e)
  })
}

/* 提交登录 */
const submit = () => {
  loginFormRef.value.validate((valid: Boolean) => {
    if (valid) {
      login(loginForm.value).then((resp: AccessToken) => {
        // 持久化token
        tokenStore.setToken(resp)

        router.push(route.query.destPath ? route.query.destPath as string : '/')
      }).catch(e => {
        getVerifyCode()
        loginForm.value.code = ''
      })
    }
  })
}

/* 重置loginForm */
const resetLoginForm = () => {
  loginFormRef.value.resetFields()
  getVerifyCode()
}

/* 组件渲染后直接执行的方法 */
getVerifyCode()
</script>

<template>
  <el-card class="login-card">
    <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginFormRules"
        label-width="80">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="loginForm.username" placeholder="请输入用户名"/>
      </el-form-item>
      <el-form-item label="密  码" prop="password">
        <el-input type="password" v-model="loginForm.password" placeholder="请输入密码"/>
      </el-form-item>
      <el-row :gutter="15">
        <el-col :span="16">
          <el-form-item label="验证码" prop="code">
            <el-input v-model="loginForm.code" placeholder="请输入验证码"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label-width="20">
            <el-image :src="codeUrl" @click="getVerifyCode"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item>
        <el-button type="primary" plain @click="submit">登录</el-button>
        <el-button type="info" plain @click="resetLoginForm">取消</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>
<style scoped>
.login-card {
  width: 400px;
  position: absolute;
  left: 50%;
  top: 50%;
  /* 向左向上移动自身的一半 */
  transform: translate(-50%, -50%);
}
</style>